Move activity to foreground when screen is in off state
Posted By : Chandan Wadhwa | 22-Sep-2014
Sometimg there's a situation when we want to take the response from activity when the screen is in off state. So there is a need to open the activity and automatically unlocking phone.
Implementation scenario -
1) In case of alarm app when phone screen is in off state although alarm app starts, phone screen unlocked automatically and activity comes to foreground.
2) In case when app response via shaking the phone and when phone screen is in off state, although we want to that activity will respond.
Step by step implementation is given below -
1) Add android:showOnLockScreen="true" property to the target activity
Example:-
2) Override the onAttachedToWindow() method from activity class. This method is called when view is attach to window.
@Override
public void onAttachedToWindow() {
// TODO Auto-generated method stub
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_FULLSCREEN
);
super.onAttachedToWindow();
}
Activity will be reopen after 3 second when screen is in off state
public class ScreenActivity extends Activity {
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent intent=new Intent(getApplicationContext(),ScreenActivity.class);
startActivity(intent);
}
}, 3000);
}
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Chandan Wadhwa
Chandan is an Android Apps developer with good experience in building native Android applications.